package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"wechat/models/mysql"
	"wechat/models/redisInit"
	"wechat/pkg"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)

	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前手机号已被注册，请更换手机号")
	}

	get := redisInit.Client.Get("sendSms" + "register" + in.Mobile)

	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新发送")
	}

	number := rand.Intn(90000) + 10000

	wechatName := fmt.Sprintf("wx%d%s", number, time.Now().Format("20060102150405"))

	user := mysql.User{
		HeadImage:  in.HeadImage,
		Name:       in.Name,
		Address:    in.Address,
		Mobile:     in.Mobile,
		PassWord:   pkg.Md5(in.Password),
		WechatName: wechatName,
	}

	err := mysql.DB.Debug().Create(&user).Error

	if err != nil {
		return nil, err
	}

	return &userrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
